package com.bigdata.security.shiro.realm;/**
 * Created by Administrator on 2019/7/9 0009.
 */


import java.util.HashSet;
import java.util.Set;

import com.bigdata.security.shiro.token.OAuth2Token;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.bigdata.common.constant.Constants;
import com.bigdata.common.em.CommonEnum;
import com.bigdata.model.User;
import com.bigdata.mysql.entity.JkfwUser;
import com.bigdata.service.mysql.JkfwUserService;
import com.bigdata.utils.shiro.ShiroUtils;

/**
 * 自定义Realm 处理登录 权限
 *
 * @author lly
 */
public class UserRealm extends AuthorizingRealm {
    private static final Logger log = LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    JkfwUserService jkfwUserService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        User user = ShiroUtils.getSysUser();
        // 角色列表
        Set<String> roles = new HashSet<String>();
        // 功能列表
        Set<String> menus = new HashSet<String>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            info.addRole("sys");
            info.addStringPermission("*:*:*");
        } else {
//            roles = roleService.selectRoleKeys(user.getUserId());
//            menus = menuService.selectPermsByUserId(user.getUserId());
//            // 角色加入AuthorizationInfo认证对象
//            info.setRoles(roles);
//            // 权限加入AuthorizationInfo认证对象
//            info.setStringPermissions(menus);
        }
        return info;
    }

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (token instanceof OAuth2Token) {
            //还没开启token 登录
            return null;
        } else {
            return doGetUsernamePasswordToken(token);
        }
    }

    private AuthenticationInfo doGetUsernamePasswordToken(AuthenticationToken token) {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = "";
        if (upToken.getPassword() != null) {
            password = new String(upToken.getPassword());
        }
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new UnknownAccountException("账号不存在！");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < Constants.USERNAME_MIN_LENGTH || username.length() > Constants.USERNAME_MAX_LENGTH) {
            throw new IncorrectCredentialsException("用户名限制2-20字符之间！");
        }
        if (password.length() < Constants.PASSWORD_MIN_LENGTH || password.length() > Constants.PASSWORD_MAX_LENGTH) {
            throw new IncorrectCredentialsException("密码限制5-20字符之间！");
        }
        JkfwUser user = null;
        try {
            user = jkfwUserService.queryUserLogin(username);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new AuthenticationException("登录系统失败！");
        }
        if (user == null) {
            throw new UnknownAccountException("账号不存在！");
        }
        if (user.getStatus().intValue() != CommonEnum.UserStatus.ok.getIdx()) {
            accountUserStat(user.getStatus());
        }

        User u = new User();
        u.setUserName(user.getUsername());
        u.setUserId(user.getUserId());
        u.setPassword(user.getPassword());
        u.setEmail(user.getEmail());
        u.setSalt(user.getSalt());
        u.setLoginName(user.getName());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(u, u.getPassword(), ByteSource.Util.bytes(CodecSupport.toBytes(u.getSalt(), "UTF-8")), getName());
        return info;
    }

    private void accountUserStat(int state) {
        if (state == CommonEnum.UserStatus.lock.getIdx()) {
            throw new LockedAccountException("账户已锁定！");
        } else {
            throw new UnknownAccountException("账户不存在！");
        }
    }

    /**
     * 清理缓存权限
     */
    public void clearCachedAuthorizationInfo() {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

}